package com.kinon.ceshiaccount.network;

import android.os.NetworkOnMainThreadException;
import android.util.Log;

import com.google.gson.JsonSyntaxException;
import com.kinon.ceshiaccount.constant.Constant;

import org.json.JSONException;
import org.json.JSONObject;

import java.net.SocketTimeoutException;
import java.net.UnknownHostException;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by luohao on 2017-07-25.
 */

public abstract class StrCallback<T> implements Callback<String> {

    private final String TAG = "lh_mycallback";

    @Override
    public void onResponse(Call<String> call,
                           Response<String> response) {
//        Gson gson=new Gson();
        try {
            JSONObject object = new JSONObject(response.body());
            if (object.getBoolean("code")) {
                T str = (T) object.getString("data");
                onSuccess(response, str);
            } else {
                logError(200, object.getString("msg"));
            }
        } catch (Exception e) {
            e.printStackTrace();
            logError(201, "数据异常");
        }
    }

    @Override
    public void onFailure(Call<String> call, Throwable t) {
        Log.e(TAG, "t== " + t.toString());
        if (t instanceof SocketTimeoutException) {
            logError(Constant.ERROR_TIMEOUT_CODE, "网络请求超时");
        } else if (t instanceof JSONException || t instanceof JsonSyntaxException) {
            logError(-3, "数据解析异常");
        } else if (t instanceof NetworkOnMainThreadException ||
                t instanceof UnknownHostException) {
            logError(-3, "网络异常,请检查网络");
        } else {
            logError(-3, "获取信息失败");
        }

    }


    private void logError(int code, String error) {
        Log.e(TAG, "code==" + code + "--error==" + error);
        onError(code, error);
    }

    public abstract void onSuccess(Response<String> response, T data) throws JSONException;

    public abstract void onError(int code, String error);
}
